package com.newbee.sustainability.web.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.newbee.sustainability.common.vo.ResponseVo;
import com.newbee.sustainability.web.service.IUserBusinessFegnCilent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserBusinessFegnCilent iUserBusinessFegnCilent;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping()
    public ResponseVo<String> save(@RequestBody Map<String, String> user) {
        String result = iUserBusinessFegnCilent.save(user);
        LOGGER.info("result:{}", result);
        return new ResponseVo<String>().success(result);
    }

    @GetMapping()
    public ResponseVo<String> info() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            LOGGER.info("eureka server: {}", service);
        }
        String info = iUserBusinessFegnCilent.info();
        return new ResponseVo<String>().success(info);
    }

    @GetMapping("/oneUser/{id}")
    @HystrixCommand(fallbackMethod = "getUserFallBack")
    public ResponseVo<String> oneUser(@PathVariable("id") String id) {
        String forObject = restTemplate.getForObject("http://user-business/user/getUser/" + id, String.class);
        return new ResponseVo<String>().success(forObject);
    }

    @GetMapping("/getUser/{id}")
//    @HystrixCommand(fallbackMethod = "getUserFallBack")
    public ResponseVo<String> getUser(@PathVariable("id") String id) {
        String info = iUserBusinessFegnCilent.getUser(id);
        return new ResponseVo<String>().success(info);
    }

    public ResponseVo<String> getUserFallBack(String id) {
        return new ResponseVo<String>().error("fallback by hystrix!");
    }
}
